import os

import openpyxl
from abc import ABC, abstractmethod
from openpyxl.styles.colors import RGB
from typing import List, Dict, Union, Optional, Any

from src.write_excel_report_data import WriteReportEntity


def is_red_font(font):
    try:
        # 统一转换为字符串处理
        if isinstance(font.color.rgb, RGB):
            hex_str = str(font.color.rgb).upper()  # 直接转换RGB对象为字符串
        else:
            hex_str = str(font.color.rgb or "").upper()

        # 处理不同颜色格式（带/不带Alpha通道）
        return any(hex_str.endswith(pattern) for pattern in ["FF0000", "FF FF0000"])
    except AttributeError:
        return False


def generate_write_report_data(convent_read_data, config):
    return [entity.execute_logic(config) for entity in convent_read_data]


class ExcelProcessor:
    def __init__(self, config):
        self.config = config
        self.wb = None
        self.df = None

    def read_base_data(self):
        """加载Excel文件"""
        try:
            self.wb = openpyxl.load_workbook(self.config['excel_path'])
            return [
                [any(is_red_font(cell.font) for cell in row)]
                + [cell.value for cell in row]
                for row in self.wb.active.iter_rows()
            ]
        finally:
            if hasattr(self, 'wb') and self.wb:
                self.wb.close()


class ReportStrategy(ABC):
    @abstractmethod
    def execute(self, config, entity: Any) -> WriteReportEntity:
        pass


class Type1Strategy(ReportStrategy):
    def execute(self, config, entity: Any) -> WriteReportEntity:
        # 生成红标报告
        output_folder = config['output_image_dir']
        os.makedirs(output_folder, exist_ok=True)

        if entity.has_red:
            entity.export_red_report(output_folder)

        return WriteReportEntity(
            position_no=entity.position_no,
            description=entity.description,
            nominal_value=entity.nominal,
            unit=entity.unit,
            upper_tolerance=entity.usl,
            lower_tolerance=entity.lsl,
            min_val=min(entity.cavities),
            max_val=max(entity.cavities),
            nominal_value_da=entity.nominal,
        )


class Type2Strategy(ReportStrategy):
    def execute(self, config, entity: Any) -> WriteReportEntity:
        return WriteReportEntity(
            position_no=entity.position_no,
            description=entity.description,
            nominal_value=entity.nominal,
            unit=entity.unit,
            upper_tolerance=entity.usl,
            lower_tolerance=entity.lsl,
            min_val=min(entity.cavities),
            max_val=max(entity.cavities),
            nominal_value_da=entity.nominal,
            comments_remarks="1"
        )
